package io.sage.modules.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;

@Component
public class XmlToDocxUtil {
    protected static Logger logger = LoggerFactory.getLogger(XmlToDocxUtil.class);
    //private static final String basePath = XmlToDocxUtil.class.getResource("/printTemplate").getPath();
    private static String pdfPrintTemplatePath;
    
    @Value("${web.pdf-printTemplate}")
    public void setPdfPrintTemplatePath(String pdfT) {
        pdfPrintTemplatePath = pdfT;
    }
    /**
     * 生成docx
     *
     * @throws Exception
     */
    public static void makeWordUUID(Map<String, Object> param, String uuid) throws Exception {
        /** 初始化配置文件 **/
        @SuppressWarnings("deprecation")
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        String fileDirectory = pdfPrintTemplatePath;
        /** 加载文件 **/
        configuration.setDirectoryForTemplateLoading(new File(fileDirectory + "/question/in"));
        /** 加载模板 **/
        Template template = configuration.getTemplate("document.xml");
        /** 准备数据 **/
        // Map<String,Object> param = new HashMap<String, Object>();
        /** 指定输出word文件的路径 **/
        String outFilePath = pdfPrintTemplatePath + "/question/out/" + uuid + ".xml";
        File docFile = new File(outFilePath);
        docFile.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(docFile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"), 10240);
        template.process(param, out);
        if (out != null) {
            out.close();
        }
        if (fos != null) {
            fos.close();
        }
        try {
            ZipInputStream zipInputStream = ZipUtils
                    .wrapZipInputStream(new FileInputStream(new File(pdfPrintTemplatePath + "/question/in/docx.zip")));
            String str = pdfPrintTemplatePath + "/question/out/" + uuid + ".docx";
            ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(new FileOutputStream(new File(str)));
            String itemname = "word/document.xml";
            ZipUtils.replaceItem(zipInputStream, zipOutputStream, itemname, new FileInputStream(new File(outFilePath)));
            System.out.println("success");

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 生成pdf
     */
    public static void makePdfByXcodeUUID(String uuid) {
        //long startTime = System.currentTimeMillis();
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(new File(pdfPrintTemplatePath + "/question/out/" + uuid + ".docx")));
            //    document.setParagraph(new Pa );
            File outFile = new File(pdfPrintTemplatePath + "/question/out/" + uuid + ".pdf");
            outFile.getParentFile().mkdirs();
            OutputStream out = new FileOutputStream(outFile);
            //    IFontProvider fontProvider = new AbstractFontRegistry();
            PdfOptions options = PdfOptions.create();
            //中文字体处理
            options.fontProvider(new IFontProvider() {

                @Override
                public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
                    try {
                        BaseFont bfChinese = BaseFont.createFont(pdfPrintTemplatePath+"/question/in/pdf_font.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                        Font fontChinese = new Font(bfChinese, 12, style, color);
                        if (familyName != null){
                            fontChinese.setFamily(familyName);
                        }
                        return fontChinese;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });
            PdfConverter.getInstance().convert(document, out, options);
            if (out != null) {
                out.close();
            }
            if(document != null){
                document.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // System.out.println("Generate ooxml.pdf with " + (System.currentTimeMillis() - startTime) + " ms.");
    }


    /**
     * 格式化String
     *
     * @param str
     * @return
     */
    public static JSONObject changeStr(String str) {
        String str1 = str.substring(1, str.length() - 1);
        String str2 = str1.replace("\\", "");
        JSONObject json = com.alibaba.fastjson.JSON.parseObject(str2);
        return json;
    }
    /**
     * 获得指定文件的byte数组
     */

    private static byte[] getBytes(FileInputStream fis) {
        byte[] buffer = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return buffer;
    }
}
